<template>
  <div>
    <div>
      <BackButton></BackButton>
    </div>
    <div class="app-container" style="margin-top: 10px;">
      <el-card style="width: 100%;">
        <el-form :model="matterInfo" ref="formRef" :rules="rules" style="margin-top: 5px;width: 95%" label-width="180px">
            <!--事项信息-->
            <div>
              <ElLine :title="'事项信息'" style="font-size: 20px;margin: 10px 0"></ElLine>
              <div>

                <!-- <el-row>
                  <el-col :span="24">
                    <el-form-item label="工作任务" prop="matterName">
                      <el-select disabled v-model="matterInfo.relatedIndicatorOrTaskId" placeholder="请选择" filterable>
                        <el-option
                            v-for="task in workTaskList"
                            :key="task.targetTaskId"
                            :label="task.targetTaskName"
                            :value="task.targetTaskId"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
 -->
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="事项名称" prop="matterName">
                      <el-input disabled v-model="matterInfo.matterName" placeholder="请输入"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="22">
                    <el-form-item label="事项内容" prop="matterContent">
                      <el-input disabled type="textarea" v-model="matterInfo.matterContent"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row justify="space-between">
                  <el-col :span="11">
                    <el-form-item label="事项负责人" prop="matterResponsibleId">
                      <el-select disabled v-model="matterInfo.matterResponsibleId" placeholder="请选择"
                                 @focus="fetchRelatedPolicies" @change="handleSelectChange" filterable>
                        <el-option
                            v-for="policy in user"
                            :key="policy.value"
                            :label="policy.label"
                            :value="policy.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="完成期限" prop="completionDeadline">
                        <el-input disabled v-model="matterInfo.completionDeadline"/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row justify="space-between">
                  <el-col :span="11">
                    <el-form-item label="事项关联人" prop="em2">
                      <el-input disabled v-model="matterInfo.em2" placeholder="请先选择事项负责人"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="关联法律" prop="relatedLawId">
                      <el-select disabled v-model="matterInfo.relatedLawId" placeholder="请选择" clearable filterable>
                        <el-option
                            v-for="law in laws"
                            :key="law.value"
                            :label="law.label"
                            :value="Number(law.value)"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row justify="space-between">
                  <el-col :span="11">
                    <el-form-item label="归属部门" prop="deptId">
                      <el-input disabled v-model="matterInfo.dept" placeholder="请先选择事项负责人"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="关联制度" prop="relatedPolicyId">
                      <el-select disabled filterable v-model="matterInfo.relatedPolicyId" placeholder="请选择" clearable >
                        <el-option
                            v-for="policy in relatedPolicies"
                            :key="policy.value"
                            :label="policy.label"
                            :value="Number(policy.value)"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>


                <el-row justify="space-between">
                  <el-col :span="11">
                    <el-form-item label="关键节点类型" prop="workContentType">
                      <el-radio-group disabled v-model="matterInfo.workContentType">
                        <el-radio label="0">市场类</el-radio>
                        <el-radio label="1">非市场类</el-radio>
                        <!-- 添加其他单选按钮选项 -->
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="是否成立专班" prop="isSpecialTeamFormed">
                      <el-radio-group disabled v-model="matterInfo.isSpecialTeamFormed">
                        <el-radio label="0">是</el-radio>
                        <el-radio label="1">否</el-radio>
                        <!-- 添加其他单选按钮选项 -->
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>

              </div>
            </div>
            <div>
              <hr class="divider"/>
              <!--工作内容（非市场类）-->
              <div>
                <el-row type="flex" justify="space-between" align="middle">
                  <el-col :span="11">
                    <ElLine :title="'关键节点（市场类）'" v-if="matterInfo.workContentType=='0'"/>
                    <ElLine :title="'关键节点（非市场类）'" v-if="matterInfo.workContentType=='1'"/>
                  </el-col>
                  <el-col  style="margin-top: 10px;">
                    <el-button type="primary" @click="addWorkContent">添加关键节点</el-button>
                  </el-col>
                </el-row>
                <div style="margin-top: 10px" v-if="matterInfo.workContentType=='0'">
                  <el-row type="flex" justify="space-between" align="middle">
                    <el-col :span="24">
                      <el-table border :data="matterInfo.workContentList" style="width: 100%"
                                :expand-row-keys="expandedRowKeys"
                                :row-key="row => row.id"   @expand-change="handleExpandClick">
                        <el-table-column type="index" label="序号" width="55"/>


                        <el-table-column label="项目名称" min-width="5%">
                          <template #default="scope">
                            <el-input class="no-border-input" v-model="scope.row.em2"
                                      placeholder="请输入" type="textarea" :rows="1"/>
                          </template>
                        </el-table-column>

                        <el-table-column label="项目金额" min-width="5%">
                          <template #default="scope">
                            <el-input class="no-border-input" v-model="scope.row.em3"
                                      placeholder="请输入" type="number" :rows="1"/>
                          </template>
                        </el-table-column>

                        <el-table-column label="项目阶段" min-width="5%">
                          <template #default="scope">
                            <el-input class="no-border-input" v-model="scope.row.em4"
                                      placeholder="请输入" type="textarea" :rows="1"/>
                          </template>
                        </el-table-column>

                        <el-table-column label="计划签单时间" min-width="5%">
                          <template #default="scope">
                            <el-date-picker
                                v-model="scope.row.signingTime"
                                type="date"
                                style="width:100%"
                                placeholder="选择日期"
                                format="YYYY/MM/DD"
                            />
                          </template>
                        </el-table-column>

                        <el-table-column label="计划回款时间" min-width="5%">
                          <template #default="scope">
                            <el-date-picker
                                v-model="scope.row.paymentCollectionTime"
                                type="date"
                                style="width:100%"
                                placeholder="选择日期"
                                format="YYYY/MM/DD"
                            />
                          </template>
                        </el-table-column>


                        <el-table-column label="关键节点" min-width="5%">
                          <template #default="scope">
                            <el-input class="no-border-input" v-model="scope.row.workContentDescription"
                                      placeholder="请输入" type="textarea" :rows="1"/>
                          </template>
                        </el-table-column>
                        <el-table-column label="节点目标" min-width="5%">
                          <template #default="scope">
                            <el-input v-model="scope.row.workGoal" placeholder="请输入" type="textarea" :rows="1"/>
                          </template>
                        </el-table-column>
                        <el-table-column label="计划完成时间" min-width="5%">
                          <template #default="scope">
                            <el-date-picker
                                v-model="scope.row.plannedCompletionTime"
                                type="date"
                                style="width:100%"
                                placeholder="选择日期"
                                format="YYYY/MM/DD"
                            />
                          </template>
                        </el-table-column>

                        <el-table-column type="expand" label="是否协同" min-width="3%">

                          <template #default="scope">

                            <div class="collaboration-list">
                              <div class="list-header">
                                <div class="list-item-content">协同需求</div>
                                <div class="list-item-content">协同目标</div>
                                <div class="list-item-content">协同人</div>
                                <div class="list-item-content">计划完成时间</div>
                                <div class="list-item-content" style="width: 60px">操作</div>
                              </div>
                              <div class="list-item" v-for="(item, index) in scope.row.workCollaborationList" :key="index">
                                <div class="list-item-content">
                                  <el-input class="no-border-input" v-model="item.collaborationNeed" placeholder="请输入协同需求" type="textarea" :rows="1" />
                                </div>
                                <div class="list-item-content">
                                  <el-input v-model="item.collaborationGoal" placeholder="请输入协同目标" type="textarea" :rows="1" />
                                </div>
                                <div class="list-item-content">
                                  <el-select multiple
                                             v-model="item.collaboratorsIdList"
                                             placeholder="请选择协同人"
                                             @focus="fetchRelatedPolicies">
                                    <el-option  v-for="policy in user"
                                                :key="policy.value"
                                                :label="policy.label"
                                                :value="policy.value" />
                                  </el-select>
                                </div>
                                <div class="list-item-content">
                                  <el-date-picker style="width: 100%" v-model="item.plannedCompletionTime" type="date" placeholder="选择日期" format="YYYY/MM/DD" />
                                </div>
                                <div class="list-item-content" style="width: 60px">
                                  <el-button class="small-btn" type="danger" @click="removeWorkCollaboration(index, scope.row)">删除</el-button>
                                </div>
                              </div>
                            </div>



                            <div style="display: flex; justify-content: flex-end;margin:1% 5% 0 0">
                              <el-button type="info" @click="addWorkCollaboration(scope.row.workCollaborationList)" style="right: 0">添加需求</el-button>
                            </div>
                          </template>
                        </el-table-column>

                        <el-table-column label="操作" min-width="5%">
                          <template #default="scope">
                            <el-button type="danger" @click="removeWorkContent(scope.$index)">删除</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-col>
                  </el-row>
                </div>




                <div style="margin-top: 10px" v-if="matterInfo.workContentType=='1'">
                  <el-row type="flex" justify="space-between" align="middle">
                    <el-col :span="24">




                      <el-table border :data="matterInfo.workContentList" style="width: 100%" :expand-row-keys="expandedRowKeys"
                                :row-key="row => row.id"   @expand-change="handleExpandClick">
                        <el-table-column type="index" label="序号" width="55"/>
                        <el-table-column label="关键节点" min-width="5%">
                          <template #default="scope">
                            <el-input class="no-border-input" v-model="scope.row.workContentDescription"
                                      placeholder="请输入关键节点" type="textarea" :rows="1"/>
                          </template>
                        </el-table-column>
                        <el-table-column label="节点目标" min-width="5%">
                          <template #default="scope">
                            <el-input v-model="scope.row.workGoal" placeholder="请输入节点目标" type="textarea" :rows="1"/>
                          </template>
                        </el-table-column>
                        <el-table-column label="计划完成时间" min-width="5%">
                          <template #default="scope">
                            <el-date-picker
                                style="width:100%"
                                v-model="scope.row.plannedCompletionTime"
                                type="date"
                                placeholder="选择日期"
                                format="YYYY/MM/DD"
                            />
                          </template>
                        </el-table-column>

                        <el-table-column type="expand" label="是否协同" min-width="2%">

                          <template #default="scope">

                              <div class="collaboration-list">
                                <div class="list-header">
                                  <div class="list-item-content">协同需求</div>
                                  <div class="list-item-content">协同目标</div>
                                  <div class="list-item-content">协同人</div>
                                  <div class="list-item-content">计划完成时间</div>
                                  <div class="list-item-content" style="width: 60px">操作</div>
                                </div>
                                <div class="list-item" v-for="(item, index) in scope.row.workCollaborationList" :key="index">
                                  <div class="list-item-content">
                                    <el-input class="no-border-input" v-model="item.collaborationNeed" placeholder="请输入协同需求" type="textarea" :rows="1" />
                                  </div>
                                  <div class="list-item-content">
                                    <el-input v-model="item.collaborationGoal" placeholder="请输入协同目标" type="textarea" :rows="1" />
                                  </div>
                                  <div class="list-item-content">
                                    <el-select multiple
                                               v-model="item.collaboratorsIdList"
                                               placeholder="请选择协同人"
                                               @focus="fetchRelatedPolicies">
                                      <el-option  v-for="policy in user"
                                                  :key="policy.value"
                                                  :label="policy.label"
                                                  :value="policy.value" />
                                    </el-select>
                                  </div>
                                  <div class="list-item-content">
                                    <el-date-picker style="width: 100%" v-model="item.plannedCompletionTime" type="date" placeholder="选择日期" format="YYYY/MM/DD" />
                                  </div>
                                  <div class="list-item-content" style="width: 60px">
                                    <el-button class="small-btn" type="danger" @click="removeWorkCollaboration(index, scope.row)">删除</el-button>
                                  </div>
                                </div>
                              </div>



                            <div style="display: flex; justify-content: flex-end;margin:1% 5% 0 0">
                              <el-button type="info" @click="addWorkCollaboration(scope.row.workCollaborationList)" style="right: 0">添加协同</el-button>
                            </div>
                          </template>
                        </el-table-column>

                        <el-table-column label="操作" min-width="3%">
                          <template #default="scope">
                            <el-button type="danger" @click="removeWorkContent(scope.$index)">删除</el-button>
                          </template>
                        </el-table-column>
                      </el-table>

                    </el-col>
                  </el-row>
                </div>
              </div>

            </div>


          <div class="button-container">
            <el-button type="primary" size="large" @click="validateForm">提交</el-button>
            <el-button type="info" size="large" @click="clearForm">清空</el-button>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script>
import {reactive, toRefs, ref, getCurrentInstance, onMounted, onBeforeUnmount} from 'vue';
import {ElInput, ElSelect, ElOption, ElRow, ElCol, ElForm, ElFormItem, ElButton, ElMessageBox, ElMessage } from 'element-plus';
import {addMatter, getSystemManage, getRelatedIndicatorOrTask,getMatter} from "@/api/matter/matter";
import {getTargetTaskList} from "../../../api/targetTask/targetTask.js";
import {getUsers} from "@/api/matter/users.js";
import {getInfo} from "../../../api/login.js";
import {getUser} from "../../../api/system/user.js";
import {useRouter} from 'vue-router';
import {saveContentAndColl} from "../../../api/matter/matter.js";


export default {
  name: "createMatter",
  props: {
    rowData: {
      type: Object,
      default: null
    }
  },
  components: {
    ElInput,
    ElSelect,
    ElOption,
    ElRow,
    ElCol,
    ElForm,
    ElFormItem,
    ElButton,
    ElMessageBox
  },

  setup(props) {
    const {proxy} = getCurrentInstance(); // 确保 proxy 获取正确
    const {related_law} = proxy.useDict('related_law');

    const router = useRouter();

    // 定义初始状态常量
    const initialMatterInfo = {
      childBorder:true,
      matterId:'',
      matterName: '', //  事项名称
      matterResponsibleId: '', // 事项
      matterRelatedPerson: '', // 事项关联人
      matterRelatedPersonId: '', // 事项关联人 id
      em2: '', // 事项关联人
      dept: '',
      deptId: '', // 部门
      relatedLawId: '', // 关联法律
      relatedPolicyId: '', // 关联制度
      relatedIndicatorOrTaskType: '1', //关联指标或任务类型
      relatedIndicatorOrTaskId: '', // 关联指标或任务类型id
      workContentType: '1', // 工作内容类型
      isSpecialTeamFormed: '1', // 是否成立专班
      completionDeadline: '', // 事项完成期限
      keyWord: '', // 关键词
      isKeyWork: '1', // 是否重要工作
      workContentList: [// 工作内容列表
        {
          workContentDescription: '',
          workGoal: '',
          plannedCompletionTime: '',
          em2: '',
          em3: '',
          em4: "",
          signingTime: '',
          paymentCollectionTime: '',
          workCollaborationList: [ // 协同需求列表
            {collaborationNeed: '', collaborationGoal: '', collaboratorsIdList: [], plannedCompletionTime: ''}
          ]
        }
      ],

    };

    const handleCollaborateChange = (row) => {
      if (row.isCollaborate && row.collaborationDetails.length === 0) {
        row.collaborationDetails.push({ collaborateDept: '', collaborateTask: '' });
      }
    };



    const expandedRowKeys = ref([])
    const handleExpandClick = (row, expandedRows) => {
      // 处理展开点击事件
      // 判断当前行是否在 expandedRows 中
      const isExpanded = expandedRows.includes(row);
      if (expandedRows.length > 0) {
        // params.test = val.test
        // // let temp = await getRequest(params)
        // val.temp = temp
        // 控制展开行
        console.log(row)
        expandedRowKeys.value = expandedRows.map((val,index) =>val.id =index);
      }else {
        expandedRowKeys.value = expandedRowKeys.value.filter((val,index) => val.id !== index);
      }


      // if (isExpanded) {
      //   console.log('Row expanded:', row);
      //   // 在这里处理展开事件
      // } else {
      //   console.log('Row collapsed:', row);
      //   // 在这里处理收起事件
      //   row.workCollaborationList = [ // 协同需求列表
      //     {collaborationNeed: '', collaborationGoal: '', collaboratorsId: '', plannedCompletionTime: ''}
      //   ]
      //
      // }

    }

    const removeWorkContent = (index) => {
      const list = data.matterInfo.workContentList;
        list.splice(index, 1);
    };

    const removeWorkCollaboration = (index, row) => {
      const list = row.workCollaborationList;

      list.splice(index, 1);

    };


    const data = reactive({
      matterInfo: initialMatterInfo,
      rules: {
        matterName: [{required: true, message: "事项名称不能为空", trigger: "blur"}],
        matterResponsibleId: [{required: true, message: "事项不能为空", trigger: "blur"}],
        matterRelatedPersonId: [{required: true, message: "事项关联人不能为空", trigger: "blur"}],
        deptId: [{required: true, message: "归属部门不能为空", trigger: "blur"}],
        // relatedLawId: [{required: true, message: "关联法律不能为空", trigger: "blur"}],
        // relatedPolicyId: [{required: true, message: "关联制度不能为空", trigger: "blur"}],
        relatedIndicatorOrTaskId: [{required: true, message: "相关指标或任务不能为空", trigger: "blur"}],
        workContentType: [{required: false}],
        isSpecialTeamFormed: [{required: false}],
        completionDeadline: [{required: false}]
      },
      departments: [], // 存储部门选项
      laws: related_law,// 存储法律法规选项
      user: [],// 存储用户选项
      relatedPolicies: [], // 存储关联制度选项
      relatedTasks: [], // 存储相关指标或任务选项
      workTaskList: [],// 工作任务集合
      deptType:'0', // 部门类型 0企业 1政府
    });

    // 事项负责人
    const fetchRelatedPolicies = () => {
      return new Promise((resolve, reject) => {
        getUsers().then(response => {
          if (response.code === 200) {
            data.user = response.data;
            console.log(data.user); // 这里改成打印正确的数据
            resolve(); // 成功获取数据后 resolve
          } else {
            proxy.$modal.msgError(result.msg);
            reject(new Error('Failed to fetch policies')); // 失败时 reject，并传递错误信息
          }
        }).catch(error => {
          console.error('Error fetching policies:', error);
          reject(error); // 捕获任何异常，并将其作为错误对象传递给 reject
        });
      });
    };

    getUsers().then(response => {
      if (response.code === 200) {
        data.user = response.data;
        console.log(data.user); // 这里改成打印正确的数据
        resolve(); // 成功获取数据后 resolve
      } else {
        proxy.$modal.msgError(result.msg);
        reject(new Error('Failed to fetch policies')); // 失败时 reject，并传递错误信息
      }
    }).catch(error => {
      console.error('Error fetching policies:', error);
      reject(error); // 捕获任何异常，并将其作为错误对象传递给 reject
    });

    const formRef = ref(null);
    getMatter(props.rowData.matterId).then(res => {
      console.log('API 响应数据:', res.data);

        // 赋值处理后的数据
        data.matterInfo = res.data;

    });



    const validateForm = () => {
// 校验数据
      if (data && data.matterInfo && data.matterInfo.workContentList && data.matterInfo.workContentList.length > 0) {
        let collaborationNeedMissing = false;
        for (const item of data.matterInfo.workContentList) {
          if (item.workContentDescription === undefined || item.workContentDescription === null
              || item.workContentDescription === '') {
            // 发现collaborationNeed没有值
            collaborationNeedMissing = true;
            ElMessage({
              message: '存在未填写的节点内容，请填写完成后再次提交！',
              type: 'warning',
              plain: true,
            })
            return;


          } else {


            if (
                item.workCollaborationList && item.workCollaborationList.length > 0
            ) {
              for (const item1 of item.workCollaborationList) {
                if (item1.collaborationNeed === undefined || item1.collaborationNeed === null || item1.collaborationNeed === '') {
                  ElMessage({
                    message: '存在未填写的协同需求，请填写完成后再次提交！',
                    type: 'warning',
                    plain: true,
                  })
                  return;
                }
              }
            }
          }
        }

      }



          let _data = {
        'matterId': data.matterInfo.matterId,
        'workCollaborationList':data.matterInfo.workContentList.workCollaborationList,
        'workContentList':data.matterInfo.workContentList
      }
      saveContentAndColl(_data).then(res => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess("保存成功");
        }
        console.log(res);
      })
    };

    // 添加工作内容
    const addWorkContent = () => {
      const lastItem = data.matterInfo.workContentList[data.matterInfo.workContentList.length - 1];
      if (lastItem && !lastItem.workContentDescription) {
        ElMessage({
          message: '请先填写最后一个节点内容！',
          type: 'warning',
          plain: true,
        })
        return;
      }
      data.matterInfo.workContentList.push({
        workContentDescription: '',
        workGoal: '',
        plannedCompletionTime: '',
        em2: '',
        em3: '',
        em4: "",
        signingTime: '',
        paymentCollectionTime: '',
        workCollaborationList: [ // 协同需求列表
          {collaborationNeed: '', collaborationGoal: '', collaboratorsIdList: [], plannedCompletionTime: ''}
        ]
      });
    };


    // 添加协同需求
    const addWorkCollaboration = (workCollaborationList) => {

      const lastItem = workCollaborationList[workCollaborationList.length - 1];
      if (lastItem && !lastItem.collaborationNeed) {
        ElMessage({
          message: '请先填写最后一个协同需求！',
          type: 'warning',
          plain: true,
        })
        return;
      }
      workCollaborationList.push({
        collaborationNeed: '',
        collaborationGoal: '',
        collaboratorsIdList: [],
        plannedCompletionTime: ''
      });
    };

    // 数据请求方法 - 获取部门选项
    const fetchDepartments = () => {
      // 这里模拟数据，实际应该通过 API 请求获取
      data.departments = [
        {value: '1', label: '部门1'},
        {value: '2', label: '部门2'},
        // 其他部门选项
      ];
    };

    // 数据请求方法 - 获取法律法规选项
    const fetchLaws = () => {
      // 这里模拟数据，实际应该通过 API 请求获取
      data.laws = [
        {value: '1', label: '法律1'},
        {value: '2', label: '法律2'},
        // 其他法律法规选项
      ];
    };


    // 选择事项后触发方法
    const handleSelectChange = (selectedId) => {
      // 根据选中的ID获取整个policy对象
      const selectedPolicy = data.user.find(policy => policy.value === selectedId);
      if (selectedPolicy) {
        // console.log('选中的政策对象：', selectedPolicy);
        data.matterInfo.matterRelatedPerson = selectedPolicy.superior
        data.matterInfo.em2 = selectedPolicy.superior // 事项关联人
        data.matterInfo.dept = selectedPolicy.dept
        data.matterInfo.deptId = selectedPolicy.deptId
      }
    };

    // 关联制度
    const systemManage = () => {
      getSystemManage().then(response => {
        if (response.code === 200) {
          data.relatedPolicies = response.data
        } else {
          proxy.$modal.msgError(result.msg);
        }
      });
    };


    const handleRelatedIndicatorOrTaskTypeChange = () => {
      data.matterInfo.relatedIndicatorOrTaskId = ''

    };



    // 模拟数据请求方法 - 获取相关指标或任务选项
    const fetchRelatedTasks = () => {
      // alert(data.matterInfo.relatedIndicatorOrTaskType)
      getRelatedIndicatorOrTask({type: data.matterInfo.relatedIndicatorOrTaskType}).then(response => {
        if (response.code === 200) {
          data.relatedTasks = response.data
        } else {
          proxy.$modal.msgError(result.msg);
        }
      });

    };


    // 清空表单
    const clearForm = () => {

      ElMessageBox.confirm(
          '确定要清空表单吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        data.matterInfo.workContentList = [// 工作内容列表
          {workContentDescription: '', workGoal: '', plannedCompletionTime: ''}
        ];
        data.matterInfo.workContentList.workCollaborationList = [ // 协同需求列表
          {collaborationNeed: '', collaborationGoal: '', collaboratorsIdList: [], plannedCompletionTime: ''}
        ];
        // formRef.value.resetFields(); // 重置表单验证状态
      }).catch(() => {
        // 用户取消了操作
      });
    };

    // // 监听传入的rowData变化，并更新matterInfo
    // watch(() => props.rowData, async (newRowData) => {
    //   if (newRowData) {
    //     data.matterInfo.matterName = newRowData.taskName;
    //     try {
    //       await fetchRelatedPolicies(); // 等待 fetchRelatedPolicies() 方法完成
    //       handleSelectChange(data.matterInfo.matterResponsibleId);
    //       fetchRelatedTaskType()
    //       data.matterInfo.relatedIndicatorOrTaskType = '1'
    //       fetchRelatedTasks()
    //
    //     } catch (error) {
    //       console.error('Error in fetchRelatedPolicies:', error);
    //       // 处理错误，例如设置默认值或显示错误信息
    //     }
    //   } else {
    //   }
    // }, {immediate: true});


    // 监听浏览器的返回事件
    const handlePopState = (event) => {

      // console.log('Popstate event detected:', event); // 输出事件对象，检查是否正确捕获到事件
      router.push('/workImplementation');
    };

    onMounted(() => {
      window.addEventListener('popstate', handlePopState);
    });

    onBeforeUnmount(() => {
      // // 示例：在组件销毁前执行路由跳转
      // router.push('/WorkImplementation/index');
    });
    const getWorkTaskList = () => {
      getTargetTaskList().then(res => {
        if (res.code == 200) {
          data.workTaskList = res.data;
        }
      })
    };
    function create(){
      getWorkTaskList();
      systemManage();
      fetchRelatedPolicies()
      fetchRelatedTasks()
    }
    create();
    return {
      ...toRefs(data),
      formRef,
      fetchDepartments,
      fetchLaws,
      validateForm,
      fetchRelatedPolicies,
      fetchRelatedTasks,
      addWorkContent,
      addWorkCollaboration,
      clearForm,
      handleSelectChange,
      handleRelatedIndicatorOrTaskTypeChange,
      systemManage,
      handlePopState,
      onMounted,
      onBeforeUnmount,
      handleCollaborateChange,
      handleExpandClick,
      removeWorkContent,
      removeWorkCollaboration

    };
  }
};
</script>


<style scoped>
.divider {
  border: none;
  border-top: 1px solid #d3d3d3; /* 灰色分割线，设置粗细 */
  width: 95%; /* 设置分割线长度 */
  margin: 30px 0; /* 上下间距 */
  position: relative;
  left: 1%; /* 向左移动 */
}

.button-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin: 50px 0; /* 上边距 */
}
.app-container {
  padding: 3px;
  margin-left: 20px;
  margin-right: 20px;
}

.collaboration-list {
  width: 100%;
  margin-left: 5%;
}

.list-header {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  font-weight: bold;
  text-align: center;
}

.list-item {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  align-items: center;
  border-bottom: 1px solid #e4e7ed;
  padding: 10px 0;
}

.list-item-content {
  padding: 0 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.small-btn {
  font-size: 12px; /* 设置较小的字体大小 */
  padding: 4px 8px; /* 设置较小的内边距 */
}


</style>
